﻿<template>
  <div>
    <Row :gutter="20">
      <Col span="6">
        <Card dis-hover>
          <div slot="title" style="margin-top:8px;">
            &nbsp;
          </div>
          <div slot="extra">
            <Row>
              <Col span="24" style="text-align: right;">
                <Button icon="md-create" type="primary"
                        @click="categoryCreate"
                        :disabled="!hasPermission('Pages.Administration.DictionaryCategories.Create')">
                  新建字典分类
                </Button>
              </Col>
            </Row>
          </div>
          <Form ref="queryForm">

            <Row :gutter="16">
              <Col span="24">
                <FormItem prop="filter" style="width:100%;margin-bottom:10px;">
                  <Input v-model="pageCategoryRequest.filter" clearable
                         placeholder="在字典分类中搜索" @on-clear="handleCategoryClear" icon="md-search"
                         @on-click="getCategoryPage" @on-enter="getCategoryPage"></Input>
                </FormItem>
              </Col>
            </Row>
          </Form>

          <div class="pandx">
            <Table ref="category" :columns="categoryColumns" :data="categoryList" :loading="categoryLoading"
                   :border="false"
                   class="margin-top-10"
                   no-data-text="没有任何数据" no-filtered-data-text="没有任何数据" :show-header="false"
                   @on-contextmenu="categoryContextMenu"
                   :show-context-menu="true" :context-menu="true" :highlight-row="false"
                   @on-row-click="categoryRowClick"
            >
              <template slot="contextMenu" slot-scope="{row}">

                <DropdownItem @click.native="categoryUpdate"
                              :disabled="!hasPermission('Pages.Administration.DictionaryCategory.Update')">更新
                </DropdownItem>
                <DropdownItem @click.native="categoryRemove"
                              :disabled="!hasPermission('Pages.Administration.DictionaryCategory.Delete')">删除
                </DropdownItem>

              </template>
            </Table>

          </div>

        </Card>
      </Col>
      <Col span="18">
        <Card dis-hover v-show="!currentRow.id">
          <div slot="title" style="margin-top:8px;">
            &nbsp;
          </div>
          请在左侧选择一个字典分类
        </Card>
        <Card dis-hover v-show="currentRow.id">
          <div slot="title" style="margin-top:8px;">
            <strong>{{ currentRow.name }}</strong> 下的字典条目
          </div>
          <div slot="extra">
            <Row style="margin-bottom:10px;">
              <Col span="24" style="text-align: right;">
                <Button icon="md-create" style="margin-right:10px;" type="primary"
                        @click="create" :disabled="!hasPermission('Pages.Administration.Dictionaries.Create')">
                  新建字典条目
                </Button>
                <Button :disabled="!hasPermission('Pages.Administration.Dictionaries.Export')" icon="md-cloud-download"
                        style="margin-right:10px;"
                        type="info" @click="download">导出到EXCEL
                </Button>

                <Button icon="md-search" type="success" @click="getPage">搜索</Button>
              </Col>
            </Row>
          </div>
          <Form ref="queryForm">
            <Row :gutter="16">
              <Col span="12">
                <FormItem prop="filter" style="width:100%;margin-bottom:10px;">
                  <Input v-model="pageRequest.filter" clearable
                         placeholder="在字典分类名、字典条目名、字典条目值、字典条目描述、创建用户中搜索" @on-clear="handleClear"></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem prop="date" style="width:100%;margin-bottom:10px;">
                  <DatePicker :editable="false" format="yyyy/MM/dd" placeholder="选择创建时间范围" placement="bottom-start"
                              split-panels style="width:100%;" type="daterange"
                              @on-change="dateChange" @on-clear="handleClear" transfer></DatePicker>
                </FormItem>
              </Col>
            </Row>

          </Form>
          <Table :columns="columns" :data="list" :loading="loading" border class="margin-top-10"
                 no-data-text="没有任何数据" no-filtered-data-text="没有任何数据" @on-sort-change="sortingChange">
            <template slot="actions" slot-scope="{row}">
              <Dropdown placement="bottom-end" transfer @on-click="handleClickActionDropdown">
                <Button size="small" type="primary">
                  操作
                  <Icon type="ios-arrow-down"></Icon>
                </Button>
                <DropdownMenu slot="list">
                  <DropdownItem :name="JSON.stringify({row:row,name:'update'})"
                                :disabled="!hasPermission('Pages.Administration.Dictionaries.Update')">更新
                  </DropdownItem>
                  <DropdownItem :name="JSON.stringify({row:row,name:'remove'})"
                                :disabled="!hasPermission('Pages.Administration.Dictionaries.Delete')">删除
                  </DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </template>
          </Table>
          <Page :current="currentPage" :page-size="pageSize" :page-size-opts="[10,20,30,40]" :total="totalCount"
                class="margin-top-10"
                show-sizer show-total @on-change="pageChange"
                @on-page-size-change="pageSizeChange">

          </Page>
        </Card>
      </Col>
    </Row>

    <dictionary-modal v-if="dictionaryModalMount" v-model="dictionaryModalShow" :modal-data="dictionaryData"
                      @save-success="getPage"></dictionary-modal>
    <dictionary-category-modal v-if="dictionaryCategoryModalMount" v-model="dictionaryCategoryModalShow"
                               :modal-data="dictionaryCategoryData"
                               @save-success="categorySaveSuccess"></dictionary-category-modal>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import DictionaryModal from '@/views/administration/dictionary/modal/dictionary-modal.vue';
import Util from '@/lib/util';
import DictionaryExpand from '@/components/expand/dictionary-expand.vue';
import PageRequest from '@/store/entities/page-request';
import CollapseTransition from '@/components/common/collapse-transition';
import DictionaryCategoryExpand from '@/components/expand/dictionary-category-expand.vue';
import DictionaryCategoryModal from '@/views/administration/dictionary/modal/dictionary-category-modal.vue';

class PageDictionaryRequest extends PageRequest {
  filter: string = '';
  sorting: string = '';
  startTime: string = '1900-01-01 00:00:00';
  endTime: string = '2099-12-31 23:59:59';
  userName: string = '';
  categoryId: number = 0;
  status: any[] = [];
}

class PageDictionaryCategoryRequest {
  filter: string = '';
}

@Component({
  components: {
    DictionaryCategoryModal,
    DictionaryModal,
    DictionaryExpand,
    CollapseTransition,
  },
})
export default class Dictionary extends AbpBase {
  name: string = 'Dictionary';

  dictionaryCategoryModalMount: boolean = false;
  dictionaryCategoryModalShow: boolean = false;
  dictionaryCategoryData: any;

  pageCategoryRequest: PageDictionaryCategoryRequest = new PageDictionaryCategoryRequest();

  currentRow: any = {};

  categoryColumns = [

    {
      align: 'left',
      width: 30,
      render: (h: any, params: any) => {
        return h('Icon', {
          props: {
            size: 18,
            type: 'ios-apps-outline',
          },
        }, []);
      },
    },
    {
      key: 'code',
      align: 'left',
      tooltip: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      key: 'name',
      align: 'left',
      tooltip: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
  ];

  advancedSearch: boolean = false;
  pageRequest: PageDictionaryRequest = new PageDictionaryRequest();

  dictionaryModalMount: boolean = false;
  dictionaryModalShow: boolean = false;
  dictionaryData: any;

  columns = [
    {
      title: '字典分类名',
      key: 'categoryName',
      align: 'center',
      width: 140,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
      sortable: this.$config.sorting.administration.dictionary,
    },
    {
      title: '字典条目名',
      key: 'name',
      align: 'center',
      width: 140,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
      sortable: this.$config.sorting.administration.dictionary,
    },
    {
      title: '字典条目值',
      key: 'value',
      align: 'center',
      width: 140,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
      sortable: this.$config.sorting.administration.dictionary,
    },
    {
      title: '字典条目描述',
      key: 'description',
      align: 'center',
      minWidth: 200,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      title: '状态',
      key: 'status',
      align: 'center',
      render: (h: any, params: any) => {
        if (params.row.status) {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.success,
              type: 'pandx fa fa-flash',
            },
          }, []);
        } else {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.disabled,
              type: 'pandx fa fa-flash',
            },
          }, []);
        }
      },
      width: 90,
      filters: [
        {
          label: '正常',
          value: 1,
        }, {
          label: '禁用',
          value: 0,
        },
      ],
      filterRemote: (array) => {
        this.pageRequest.status = array;
        this.getPage();
      },
      resizable: true,
    },
    {
      title: '显示顺序',
      key: 'orderNo',
      align: 'center',
      width: 120,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
      sortable: this.$config.sorting.administration.dictionary,
    },
    {
      title: '创建用户',
      key: 'creatorName',
      align: 'center',
      width: 120,
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
      sortable: this.$config.sorting.administration.dictionary,
    },
    {
      title: '创建时间',
      key: 'creationTime',
      align: 'center',
      width: 180,
      sortable: this.$config.sorting.administration.dictionary,
      render: (h: any, params: any) => {
        return h('span', {}, Util.getTime(params.row.creationTime));
      },
      tooltip: true,
      resizable: true,
      ellipsis: true,
      tooltipTheme: 'dark',
    },
    {
      title: '操作',
      width: 110,
      slot: 'actions',
      align: 'center',
    },
  ];


  get categoryList() {
    return this.$store.state.dictionaryCategory.list;
  }

  get categoryLoading() {
    return this.$store.state.dictionaryCategory.loading;
  }

  get list() {
    return this.$store.state.dictionary.list;
  }

  get loading() {
    return this.$store.state.dictionary.loading;
  }

  get pageSize() {
    return this.$store.state.dictionary.pageSize;
  }

  get totalCount() {
    return this.$store.state.dictionary.totalCount;
  }

  get currentPage() {
    return this.$store.state.dictionary.currentPage;
  }

  get excelFile() {
    return this.$store.state.dictionary.excelFile;
  }




  categoryRowClick(row, index) {
    this.addBackgroundColor(row);
    this.currentRow = row;
    this.getPage();

  }

  async categoryContextMenu(row, event, position) {
    this.addBackgroundColor(row);
    this.currentRow = row;
    this.getPage();
  }

  addBackgroundColor(row) {
    const tds1 = document.querySelectorAll('.highlight');
    for (const td of tds1) {
      td.classList.remove('highlight');
    }
    const index = this.categoryList.findIndex(item => item.code === row.code);
    const tds2 = document.querySelectorAll('.pandx table tr')[index].querySelectorAll('td');
    for (const td of tds2) {
      td.classList.add('highlight');
    }
  }

  async categoryCreate() {
    this.dictionaryCategoryData = {data: null, update: false};
    this.dictionaryCategoryModalMount = true;
    this.$nextTick(() => {
      this.dictionaryCategoryModalShow = true;
    });
  }

  async categoryRemove() {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要删除字典分类 ' + this.currentRow.name + ' 吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'dictionaryCategory/deleteDictionaryCategory',
          data: this.currentRow,
        });
        this.$Message.success({
          background: true,
          content: '字典分类 ' + this.currentRow.name + ' 已删除成功',
          duration: this.$config.duration,
        });
        await this.getCategoryPage();
        this.currentRow = {id: 0, name: ''};
      },
      onCancel: () => {
      },
    });
  }

  async categoryUpdate() {
    await this.$store.dispatch({
      type: 'dictionaryCategory/getDictionaryCategoryForEdit',
      data: this.currentRow,
    });
    this.dictionaryCategoryData = {data: this.currentRow, update: true};
    this.dictionaryCategoryModalMount = true;
    this.$nextTick(() => {
      this.dictionaryCategoryModalShow = true;
    });
  }

  async categorySaveSuccess(code: any) {
    await this.getCategoryPage();
    this.currentRow = this.categoryList.find(item => item.code === code);
    this.addBackgroundColor(this.currentRow);
    this.getPage()
  }



  handleCategoryClear() {
    this.getCategoryPage();
  }



  handleClear() {
    this.getPage();
  }

  async handleClickActionDropdown(name: string) {
    const temp: any = JSON.parse(name);
    switch (temp.name) {
      case 'update':
        await this.update(temp.row);
        break;
      case 'remove':
        await this.remove(temp.row);
        break;
    }
  }

  async pageChange(page: number) {
    this.$store.commit('dictionary/setCurrentPage', page);
    await this.getPage();
  }

  async pageSizeChange(pageSize: number) {
    this.$store.commit('dictionary/setPageSize', pageSize);
    await this.getPage();
  }

  async sortingChange(sorting: any) {
    if (sorting.column.sortable === 'custom') {
      if (sorting.order === 'asc' || sorting.order === 'desc') {
        this.pageRequest.sorting = sorting.key + ' ' + sorting.order;
      }
      await this.getPage();
    }
  }

  async download() {
    await this.$store.dispatch({
      type: 'dictionary/obtainDictionariesToExcel',
      data: this.pageRequest,
    });
    if (this.hasPermission('Pages.Files.Download')) {
      Util.downloadWithToken('/api/File/DownloadTempFile?fileType=' + this.excelFile.fileType + '&fileToken=' + this.excelFile.fileToken + '&fileName=' + this.excelFile.fileName, this.excelFile.fileName, this.excelFile.fileType);
    } else {
      this.$Message.error({
        background: true,
        content: '下载失败，缺少文件下载权限',
        duration: this.$config.duration,
      });
    }
  }

  async create() {
    this.dictionaryData = {data: null, update: false, list: this.categoryList, current: this.currentRow};
    this.dictionaryModalMount = true;
    this.$nextTick(() => {
      this.dictionaryModalShow = true;
    });
  }

  async remove(row: any) {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要删除字典条目 ' + row.name + ' 吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'dictionary/deleteDictionary',
          data: row,
        });
        this.$Message.success({
          background: true,
          content: '字典条目 ' + row.name + ' 已删除成功',
          duration: this.$config.duration,
        });
        await this.getPage();
      },
      onCancel: () => {
      },
    });
  }

  async update(row: any) {
    await this.$store.dispatch({
      type: 'dictionary/getDictionaryForEdit',
      data: row,
    });
    this.dictionaryData = {data: row, update: true, list: this.categoryList, current: this.currentRow};
    this.dictionaryModalMount = true;
    this.$nextTick(() => {
      this.dictionaryModalShow = true;
    });
  }


  dateChange(date: any[]) {
    this.pageRequest.startTime = (date[0] === '' ? '1900-01-01' : date[0]) + ' 00:00:00';
    this.pageRequest.endTime = (date[1] === '' ? '2099-12-31' : date[1]) + ' 23:59:59';
  }

  async getPage() {
    this.pageRequest.maxResultCount = this.pageSize;
    this.pageRequest.skipCount = (this.currentPage - 1) * this.pageSize;
    this.pageRequest.categoryId = this.currentRow.id;
    await this.$store.dispatch({
      type: 'dictionary/obtainDictionaries',
      data: this.pageRequest,
    });
  }

  async getCategoryPage() {
    await this.$store.dispatch({
      type: 'dictionaryCategory/obtainDictionaryCategories',
      data: this.pageCategoryRequest,
    });
  }


  async created() {
    await this.getPage();
    await this.getCategoryPage();
  }
}
</script>

<style lang="less" scoped>
.ivu-card::v-deep .pandx .highlight {
  background-color: #d5e8fc;
  font-weight: bolder;
}

.ivu-card::v-deep .pandx {
  height: calc(100vh - 270px);
  overflow-y: auto;
}

.ivu-card::v-deep .pandx::-webkit-scrollbar {
  width: 4px;
  background-color: #fff;
}

.ivu-card::v-deep .pandx::-webkit-scrollbar-thumb {
  border-radius: 2px;
  -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, .3);
  background-color: #e8eaec;
}

.ivu-card::v-deep .pandx::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, .3);
  border-radius: 2px;
  background-color: #fff;
}
</style>
